import {
    GET_LIST_DATA,
    CHANGE_CURRENT_INDEX,
    ADD_SELECT_ITEM,
    REMOVE_SELECT_ITEM,
    CHANGE_ISSHOW_CHOOSE,
    CLEAN_CAR
} from "../actions/actionTypes";

const initState = {
    menuData: {}, // menu全部的数据，
    currentLeftIndex: 0, // 左侧选中
    isShowChoose: false // 是否展示订单详情
}

const getMenuData  = (state, action) => {
    return { ...state, menuData: action.obj.data }
}

const changeLeftIndex = (state, action) => {
    return {...state, currentLeftIndex: action.obj.index}
}

const addSelect = (state, action) => {
    return {...state, menuData: dealSelect(state, action, 1)};
}

const removeSelect = (state, action) => {
    return {...state, menuData: dealSelect(state, action, 0)};
}

const dealSelect = (state, action, type) => {
    let listData = state.menuData;
    // 找到外层，左边list列表
    let list = listData.food_spu_tags || [];

    // 通过列表找到左边item使用的数据也就是点击的item数据
    let currentItem = list[action.obj.fu_index];

    // 对当前点击这个item的chooseCount加一或减一
    if (type === 1) {
        currentItem.spus[action.obj.sub_index].chooseCount ++;
    } else {
        currentItem.spus[action.obj.sub_index].chooseCount --;
    }

    let _listData = JSON.parse(JSON.stringify(listData));

    return _listData;
}

// 清空
const clearCar = (state) =>{

    let listData = state.menuData;
    // 找到外层，左边list列表
    let list = listData.food_spu_tags || [];

    for (let i = 0 ; i< list.length ; i++) {
        let spus = list[i].spus || [];
        for (let j = 0 ; j < spus.length ; j++) {
            spus[j].chooseCount = 0;

        }
    }

    return {...state, menuData: JSON.parse(JSON.stringify(listData)) };
}

const changeIsShowChoose = (state, action) => {
    return { ...state, isShowChoose: action.obj.isShowChoose }
}

const menuReducer = (state = initState, action) => {
    switch(action.type) {
        case GET_LIST_DATA:
            return getMenuData(state, action);
        case CHANGE_CURRENT_INDEX:
            return changeLeftIndex(state, action);
        case ADD_SELECT_ITEM:
            return addSelect(state, action);
        case REMOVE_SELECT_ITEM:
            return removeSelect(state, action);
        case CHANGE_ISSHOW_CHOOSE:
            return changeIsShowChoose(state, action);
        case CLEAN_CAR:
            return clearCar(state);
        default:
            return state;
    }
}

export default menuReducer
